<?php
/****
 * 向 接口对接 基类
 */ 
// 
class Helper_interface_base{
	public $config; //配置
	public function __construct()
	{
		
	}
	/***
	 *	基本参数
	 *

	 */
	public function __setconfig($assign){
		if(is_array($assign)) foreach($assign as $key=>$value){
			if(!(empty($key)||empty($value))){
				$this->config[$key]=$value;
			}
		}
	}
	public function __issetconfig($key){
		if(empty($key)) return  false;
		return isset($this->config[$key]);
	}
	public function __getconfig($key=null){
		if($this->__issetconfig($key)){
			return $this->config[$key];
		}else{
			return $this->config;
		}
	}
	
	/********
	 * post函数
	 *
	 * @param string $postfields 传输的内容
	 * config[postur]	 
	 */	 	 
    public function post($postfields,$timeout=10)
    {
		// create a new cURL resource
		$ch = curl_init();
		// set URL and other appropriate options
		curl_setopt($ch, CURLOPT_URL, $this->config['posturl']);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
		//SSL
		if(isset($this->config["SSL"])&&$this->config["SSL"]){
			curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
		}
		// grab URL and pass it to the browser
		if(!isset($this->config["raw_output"])||$this->config['raw_output']){
			curl_setopt ($ch, CURLOPT_BINARYTRANSFER, 0);
		}
		$return=curl_exec($ch);
		if(curl_errno($ch))
		{
		    $return='Curl error: ' . curl_error($ch);
		}
		// close cURL resource, and free up system resources
		curl_close($ch);
		return trim($return);
    }
    
	// 返回 记录 
	function _return($data){
		return $data;
	}
	/**
	 * post函数
	 *
	 * @param string $host 服务器地址
	 * @param int $port 端口
	 * @param string $path 访问的文件路径
	 * @param string $data 传输的内容
	 * @param string $header content-type 'application/x-www-form-urlencoded' / 'multipart/form-data'
	 * @return 结果数组 $fetch
	 */
    function socket_post($url, $data='', $header="",$charset="utf-8",$timeout=10)
    {
        list($host,$port,$path,$query)=$this->parseLink($url);
        if($query){
            $path.='?'.$query;
        }
        $fetch = array('header'=>'','body'=>'');
        if(!$host)
        {
            $fetch['errno'] = 0;
            $fetch['errstr'] = '无指定服务器';
            return $fetch;
        }
        $fp = fsockopen($this->config['host'], $this->config['port'], $fetch['errno'], $fetch['errstr'], $timeout);
        if($fp == false)
        {
            return $fetch;
        }
        if(isset($this->contenttype)){
			$contenttype=$this->contenttype;
		}else{
			$contenttype="application/x-www-form-urlencoded";
		}
        
        //stream_set_timeout($fp, 4);
        $sheader  = "POST {$path} HTTP/1.1\r\n";
        $sheader .= "Host: {$host}:{$port}\r\n";
        $sheader .= "Content-Type: {$contenttype}\r\n";
        $sheader .= "Accept-Charset: ".$charset.";\r\n";
        $sheader .= "Content-length: ".strlen($data)."\r\n";
        $sheader .= $header;//."\r\n";
        $sheader .= "Connection: Close\r\n\r\n";
        $sheader .= $data;
        //var_dump($sheader);die('d');
        fwrite($fp, $sheader);
        while($str = trim(fgets($fp)))
        {
        	$fetch['header'] .= $str."\r\n";
        }
        
        //$this->socket_return_body="";
        while(!feof($fp))
        {
        	$fetch['body'].=fgets($fp);
        	//$this->_socket_return(fgets($fp));
        }
        //$fetch['body']=$this->socket_return_body;
        //echo __LINE__; print_r($fetch['body']);
        fclose($fp);
        return $fetch;
    }
    /****
     * sock open post 上传文件 , 这只是 把参数组织一下,再调用 socket_post      
     * $content_type='multipart/form-data';
       $formvars 表单普通 字段 参数
		$formfiles 表单 附件
		
     */
	public function socket_filepost($formvars='',$formfiles='',$charset="utf-8",$timeout=10){
        list($host,$port,$path)=$this->parseLink($url);
        $this->_mime_boundary = "--------".md5(uniqid(microtime()));
		// 普通 字段 参数
		$data='';
		if(count($formvars))foreach($formvars as $key=>$val){
			if (is_array($val) || is_object($val)) {
				while (list($cur_key, $cur_val) = each($val)) {
					$data .= "--".$this->_mime_boundary."\r\n";
					$data .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n";
					$data .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
					$data .= "$cur_val\r\n";
				}
			} else {
				$data .= "--".$this->_mime_boundary."\r\n";
				$data .= "Content-Disposition: form-data; name=\"$key\"\r\n";
				$data .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
				$data .= "$val\r\n";
			}
		}
		//表单 附件
		if(count($formfiles))foreach($formfiles as $field_name=>$file_names){
			settype($file_names, "array");
			while (list(, $file_name) = each($file_names)) {
				if (!is_readable($file_name)) continue;
				//$mct=mime_content_type($file_name);
				$mct=Helper_Util::mimeType($file_name);
				$fp = fopen($file_name, "r");
				$file_content = fread($fp, filesize($file_name));
				fclose($fp);
				$base_name = basename($file_name);

				$data .= "--".$this->_mime_boundary."\r\n";
				$data .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n";
				if($mct) $data .= "Content-Type: $mct\r\n";
				$data .= "\r\n"."$file_content\r\n";
			}
		}
		$data .= "--".$this->_mime_boundary."--\r\n";
		$content_type='multipart/form-data ;boundary='.$this->_mime_boundary;
		$fp = fsockopen($host, $port, $fetch['errno'], $fetch['errstr'], $timeout);
        if($fp == false)
        {
            return $fetch;
        }
        $sheader  = "POST {$path} HTTP/1.1\r\n";
        $sheader .= "Host: {$host}\r\n";
        $sheader .= "Content-Type: ".$content_type."\r\n";
        $sheader .= "Accept-Charset: ".$charset.";\r\n";
        $sheader .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\r\n";
        $sheader .= "Content-length: ".strlen($data)."\r\n";
        $sheader .= "Keep-Alive: timeout=15, max=100\r\n";
        $sheader .= "Connection: keep-alive\r\n\r\n"; //close
        $sheader .= $data;
//        var_dump($data);die('fff');
        //发送
        fwrite($fp, $sheader);
        $fetch['header']='';
        while($str = trim(fgets($fp)))
        {
        	$fetch['header'] .= $str."\r\n";
        }
        $fetch['body']='';
        while(!feof($fp))
        {
        	$fetch['body'].=fgets($fp);
        }
        fclose($fp);
        return $fetch;
	}
	/****
	 * Get 用curl()函数 使用   
	 */
    public function cget($url,$timeout=10){
		ob_start();
		// create a new cURL resource
		$ch = curl_init();
		// set URL and other appropriate options
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		// grab URL and pass it to the browser
		curl_exec($ch);
		// close cURL resource, and free up system resources
		curl_close($ch);
		$return=ob_get_clean();
		return trim($return);
	}
	/*****
	 * Get 用fopen 函数 
	 * 
	 */	 	 	
	public function fget($url,$timeout=0){
		if($timeout){
			$old_timeout=ini_get('default_socket_timeout');
			ini_set('default_socket_timeout',$timeout);
		}
		$contents=file_get_contents($url);
		if(isset($old_timeout)){
			ini_set('default_socket_timeout',$old_timeout);
		}
		return $contents;
	}
    /***
     * 处理 socket open post后的 返回
     * 只针对 body的 
	 **/
    function _socket_return($row){
		$this->socket_return_body.=$row;
	}
	//将 post字段 组成 字符串
	function formatpoststr($postDataArr,$leftAnd=0){
		$postfieldstr="";
		foreach($postDataArr as $k=>$v){
			if (is_array($v) || is_object($v)){
				while (list($cur_key, $cur_val) = each($v)) {
					$postfieldstr.="&".urlencode($k)."[]=".urlencode($cur_val);
				}
			}else{
				$postfieldstr.="&".urlencode($k)."=".urlencode(stripslashes($v));
			}
		}
		if(!$leftAnd){
			$postfieldstr=ltrim($postfieldstr,'&');
		}
		return $postfieldstr;
	}
	/**
	 *  将参数 附加到 url 后 ,用于 Get 方式的 url 
	 */
	function buildUrl($baseUrl,$params){
		$paramsstr=$this->formatpoststr($params,1);
		if(strpos($baseUrl,"?")==false){
			$url=$baseUrl."?".$paramsstr;
		}elseif(stripos($baseUrl,"?")==0||stripos($url,"&")==0){
			$url=$baseUrl.$paramsstr;
		}else{
			$url=$baseUrl."&".$paramsstr;
		}
		return $url;
	}
    /**
    * Extra the http url
    *
    * @param $link
    *  host,path,scheme
    */
    public function parseLink($url)
    {
        $this->config['port']=80;
        $this->config['scheme']='http';
    	$this->config['url'] = $url;
    	$this->components = parse_url($this->config['url']);
    	$this->config=array_merge($this->config,$this->components);
    	$this->config['filename'] = basename($this->config['path']);
    	if($this->config['port'] == 443){
			$this->config['scheme']='SSL';
		}
		$this->config['referer'] = $this->config['scheme'] . '://' . $this->config['host'];
		return array(
            $this->config['host'],$this->config['port'],$this->config['path'],$this->config['query']
        );
    }
    
	//读到config 文件
	function _loadconfig(){

	}
	//取微秒数做为 记录标
	function microsec(){
		list($usec,$sec)=explode(" ",microtime());
		return $sec.(int)($usec*1000000).rand(10,99);
	}
}